<template>
	<view>
		<view class="flex justify-around  padding">
			<!-- <view class="flex-sub text-white text-center">答题记录</view>
			<view class="flex-sub text-white text-center">规则说明</view> -->
		</view>
		<!-- 头像区域 -->

		<view v-if="!isInvite" class="flex flex-direction justify-center align-center" style="height: 365px;width: 100%;">
			<view class="cu-avatar xl round " :style="'background-image: url(' + userinfo.avatarUrl + ');'">
				<view class="cu-tag badge light	 bg-blue">发起者</view>
			</view>
			<!-- 名字 -->
			<view class="text-xxl text-white margin-top text-bold">{{ userinfo.nickName }}</view>
			<!-- 积分 -->
			<!-- <view class="text-xxl text-white margin-top text-bold">积分:120</view> -->

		</view>

		<view v-else class="flex flex-direction justify-center align-center" style="height: 365px;width: 100%;">
			<view class="cu-avatar xl round " :style="'background-image: url(' + senderAvatar + ');'">
				<view class="cu-tag badge light	 bg-blue">发起者</view>
			</view>
			<!-- 名字 -->
			<view class="text-xxl text-white margin-top text-bold">{{ sender }}</view>
			<!-- 积分 -->
			<view class="text-xxl text-white margin-top text-bold">邀请你进行PK</view>

		</view>

		<view v-if="loginFlag == false" class="flex justify-center align-center" style="width: 100%;">
			<view class="flex justify-center align-center justify-around" style="height: 130px;width: 340px;gap: 10px;">
				<button class="flex flex-sub flex-direction justify-center align-center radius"
					style="background: #FF9797;height: 100%;">
					<view class="iconsize icon1"> </view>
					<view class="text-xl text-white text-bold">请先登录</view>
				</button>
			</view>

		</view>

		<view v-else-if="!isInvite && loginFlag == true" class="flex justify-center align-center" style="width: 100%;">
			<view class="flex justify-center align-center justify-around" style="height: 130px;width: 340px;gap: 10px;">
				<button open-type="share" class="flex flex-sub flex-direction justify-center align-center radius"
					style="background: #FF9797;height: 100%;">
					<view class="iconsize icon1"> </view>
					<view class="text-xl text-white text-bold">邀请好友</view>
				</button>
			</view>
		</view>

		<!-- 被邀请者看见的 -->
		<view v-else-if="isInvite && loginFlag == true" class="flex justify-center align-center" style="width: 100%;">
			<view class="flex justify-center align-center justify-around" style="height: 130px;width: 340px;gap: 10px;">
				<button @click="acceptPk()" class="flex flex-sub flex-direction justify-center align-center radius"
					style="background: #FF9797;height: 100%;">
					<view class="iconsize icon1"> </view>
					<view class="text-xl text-white text-bold">接受邀请</view>
				</button>
			</view>

		</view>



		<view v-if="loadModal" @tap="cancel()" class="text-xl bg-white qxpp">取消等待</view>
		<view class="cu-load load-modal" v-if="loadModal">
			<!-- <view class="cuIcon-emojifill text-orange"></view> -->
			<view class="gray-text">等待邀请响应...</view>
		</view>
	</view>
</template>

<script>
// import {
// 	mapState
// } from 'vuex'
import loginjs from '../../core/login'
export default {
	data() {
		return {
			data: {
				onMessageListPage: true, //是否在消息列表页
				socketOpen: false, //是否开启了websocket
				current_passive_uid: -1, //当前聊天对象
				heartbeat_delay: 50000, //心跳时间
				message_page: 1, //当前消息列表页面，每页20个列表
				message_list: [], //用于渲染的消息列表数据
				unreadcount: 0, //总未读消息数
				reconnect_delay: 5000, //重连延迟
				eventChannel: null //与chat的通信接口
			},
			userinfo: {},//用户信息
			sendUserId: -1,//发送者userid -1为未发出邀请的状态
			isInvite: false,//是否被邀请
			match_id: '',//比赛id
			loadModal: false,//匹配中
			isSend: true,
			sender: '',
			senderAvatar: '',
			loginFlag: true,//是否登录标记，默认登录


		}
	},
	computed: {
		// ...mapState(['userinfo']),
	},
	methods: {
		getUserInfo() {//islogin 进来 登录才会来到这里
			// let res = await this.$myHttp.post({
			// 	url: this.$myHttp.urlMap.userInfo,
			// 	needLogin: true
			// })
			// if (res.code == 1) {
			// 	this.user_info = res.data
			// 	console.log('%c [ this.userinfo ]-111', 'font-size:13px; background:pink; color:#bf2c9f;', this.user_info)
			// }
			let token = JSON.parse(uni.getStorageSync('vuexvuex'))
			var parsedData = JSON.parse(token.value);
			this.userinfo = parsedData.userinfo;
			console.log('%c [ this.userinfo ]-122', 'font-size:13px; background:pink; color:#bf2c9f;', this.userinfo)
		},
		cancel() {
			this.loadModal = false
			let token = JSON.parse(uni.getStorageSync('vuexvuex'))
			var parsedData = JSON.parse(token.value);
			var tokenValue = parsedData.userinfo.token;
			this.sendMsg({
				"type": "cancel_matching",
				"token": tokenValue,
				"match_type": 1
			})

		},
		//接受了pk


		// 接受pk
		acceptPk() {
			console.log('接受了pk')
			uni.showToast({
				title: '连接中...',
				icon: 'none',
				mask: true
			})
			let token = JSON.parse(uni.getStorageSync('vuexvuex'))
			var parsedData = JSON.parse(token.value);
			var tokenValue = parsedData.userinfo.token;
			this.sendMsg({
				"type": "matching",
				"token": tokenValue,
				"match_type": 1,
				'join_type': 1,
				'match_id': this.match_id
			})
		},
		sendPk() {
			console.log('发送给了');
			let token = JSON.parse(uni.getStorageSync('vuexvuex'))
			var parsedData = JSON.parse(token.value);
			var tokenValue = parsedData.userinfo.token;
			this.sendMsg({
				"type": "matching",
				"token": tokenValue,
				"match_type": 1,
				'join_type': 0
			})
		},
		islogin() {
			if (loginjs.checkIfLogin() == false) {
				this.loginFlag = false
				// 弹窗提示请登录后操作
				uni.showToast({
					title: '请先登录',
					icon: 'none',
					mask: true,
					duration: 1000,
				})
				uni.navigateTo({
					url: '/pages/auth/login/index'
				})
			} else {
				this.loginFlag = true
				this.getUserInfo()
			}
		},
		sendMsg(data) {
			wx.sendSocketMessage({
				data: JSON.stringify(data)
			})
			console.log('发送了isSend')
			this.isSend = true

		},
		openWebSocket() {
			let that = this
			let token = JSON.parse(uni.getStorageSync('vuexvuex'))
			var parsedData = JSON.parse(token.value);
			var tokenValue = parsedData.userinfo.token;

			wx.connectSocket({
				url: that.$myHttp.urlMap.chat,
				header: {
					'content-type': 'application/json',
					'from': 'wechatmini'
				}
			})
			wx.onSocketMessage((msg) => {
				let data = JSON.parse(msg.data)
				console.log('webdata: ', data)

				switch (data.data.type) {
					case 'opponent_winner':
						console.log('opponent_winner,我赢了')
						uni.$emit('yingle')
						break;
					case 'opponent_loser':
						console.log('opponent_loser,我输了')
						uni.$emit('shule')
						break;
					case 'exit_matching_success':
						console.log('exit_matching_success,我退出了')
						uni.$emit('shule')
						break;
					case 'exit_matching_failed':
						console.log('exit_matching_failed,我退出失败了')
						uni.$emit('shule')
						break;
					case 'cannot_win':
						console.log('cannot_win,异常错误')
						uni.$emit('shule')
						break;

					case 'matching_wait':
						//等待
						that.loadModal = true
						console.log('等待matching_wait')
						// data.match_id
						this.match_id = data.data.match_id
						console.log('%c [ this.match_id ]-197', 'font-size:13px; background:pink; color:#bf2c9f;', this.match_id)
						break;
					case 'matching_success':
						//成功
						console.log('成功状态matching_success')

						setTimeout(() => {
							that.loadModal = false
							uni.showToast({
								title: '匹配成功',
								icon: 'success',
								duration: 3000
							})

						}, 1000);


						setTimeout(() => {
							that.$openrul('/pages/randomPk/randomPk?my=' + JSON.stringify(that.userinfo) + '&orther=' + msg.data + '&type=1')
						}, 3000);

						//跳转
						break;
					case 'matching_error':
						//错误状态
						console.log('错误状态matching_error')
						setTimeout(() => {
							that.loadModal = false
							uni.showToast({
								title: '匹配失败',
								icon: 'error',
								duration: 2000
							})
						}, 1000);
						// 提示，出现错误
						break;
				}
			})
			wx.onSocketOpen((msg) => {
				that.data.socketOpen = true
				that.sendMsg({
					type: 'login',
					token: tokenValue
				})
				console.log('WebSocket登录')
				//心跳
				that.data.pong = setInterval(() => {
					that.sendMsg({
						type: 'pong'
					})
				}, that.data.heartbeat_delay);
			})
			wx.onSocketClose((msg) => {
				clearInterval(that.data.pong)
				//reconnect
				that.data.socketOpen = false
				let i = setInterval(() => {
					wx.connectSocket({
						url: that.$myHttp.urlMap.chat,
						header: {
							'content-type': 'application/json',
							'from': 'wechatmini'
						}
					})
					console.log('reconnect')
					if (that.data.socketOpen) clearInterval(i)
				}, that.data.reconnect_delay)
			})
		},
	},

	onShareAppMessage() { // 分享到微信好友
		// 发送匹配请求
		console.log('点击了分享');
		console.log('%c [ this.match_id ]-275', 'font-size:13px; background:pink; color:#bf2c9f;', this.match_id)
		this.sendPk()
		return new Promise((resolve, reject) => {
			wx.showLoading({
				title: '正在请求分享数据...',
				icon: 'none'
			})
			setTimeout(() => { // 模拟异步请求的动作，1秒之后返回数据
				wx.hideLoading()
				resolve({
					title: `${this.userinfo.nickName}邀请你来挑战答题！赶快加入吧!`,
					path: `/pages/pkAnswer/pkAnswer?userid=${this.userinfo.user_id}&matchid=${this.match_id}&name=${this.userinfo.nickName}&avatar=${this.userinfo.avatarUrl}`,
					imageUrl: 'https://p5.itc.cn/q_70/images03/20201114/4a5c63f438a24624a0ed6a7395657568.jpeg',
				})
			}, 1000)

		})
	},

	onShow() {
		this.islogin()
		//检查是否被邀请
		if (this.sendUserId !== -1) {
			if (this.sendUserId !== this.userinfo.user_id) {
				this.isInvite = true//被邀请的
				console.log('%c [ 被邀请的 ]-329', 'font-size:13px; background:pink; color:#bf2c9f;', '被邀请的')
			}
		}

	},
	onLoad(options) {
		//本地存储 type=1
		uni.setStorageSync('type', 1)//当前为pk 完成答题跳转再来一次用的标记
		console.log('%c [ options ]-293', 'font-size:13px; background:pink; color:#bf2c9f;', options)
		this.openWebSocket()

		if (options.userid) {
			this.sendUserId = Number(options.userid)
			this.match_id = options.matchid
			this.sender = options.name
			this.senderAvatar = options.avatar
		}

	}

}
</script>

<style>
.qxpp {
	position: fixed;
	top: 0;
	right: 0;
	bottom: -300rpx;
	left: 0;
	margin: auto;
	width: 260rpx;
	height: 50rpx;
	background-color: #ffffff;
	border-radius: 10rpx;
	display: flex;
	align-items: center;
	flex-direction: column;
	justify-content: center;
	font-size: 28rpx;
	z-index: 99999;
	line-height: 2.4em;
}

page {
	background-image: url('');
	background-size: cover;
}

.iconsize {
	width: 53px;
	height: 53px;
}

.icon1 {
	background-image: url('');
	background-size: cover;
}

.icon2 {
	background-image: url('');
	background-size: cover;
}
</style>
